package com.carkeeper.serve.controller;


import com.carkeeper.entity.Result;
import com.carkeeper.entity.StatusCode;
import com.carkeeper.util.FastDFSClient;
import com.carkeeper.util.FastDFSFile;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FileController {


    @PostMapping("/upload")
    public Result upload(@RequestBody MultipartFile[] fileList) {
        //判断file对象是否为空
        if (fileList == null || fileList.length <= 0) {
            return new Result(false, StatusCode.ERROR, "文件为空！");
        }
        String url = "";
        for (MultipartFile file : fileList) {
            //声名url

            //获取文件名
            String originalFilename = file.getOriginalFilename();
            //获取后缀名不包括.
            String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            try {
                //创建fastdfs文件对象
                FastDFSFile fastDFSFile = new FastDFSFile(suffix, file.getBytes(), "");
                //上传文件
                String[] upload = FastDFSClient.upload(fastDFSFile);
                //upload为
                //拼接图片访问地址进行封装返回
                url += FastDFSClient.getTrackerUrl()+ upload[0] + "/" + upload[1]+",";

            } catch (IOException e) {
                e.printStackTrace();
                return new Result(false, StatusCode.ERROR, "文件上传失败！");
            }
        }
        url = url.substring(0, url.length() - 1);

        return new Result(true, StatusCode.OK, "文件上传成功！", url);



    }


}
